<template>
    <div class="search-container">
        <div class="search-box">
            <div class="search-input-wrapper">
                <input 
                    type="text" 
                    v-model="searchKeyword" 
                    @input="handleInput" 
                    @blur="handleBlur"
                    placeholder="请输入地址" 
                    class="search-input"
                />
                <button @click="handleSearchButton" class="search-button" :class="{ 'loading': searchLoading }">
                    <van-icon :name="searchLoading ? 'loading' : 'search'" size="20" />
                </button>
            </div>
            <div v-if="showSuggestions && searchKeyword" class="suggestions-container">
                <div v-if="searching" class="suggestion-loading">
                    <div class="suggestion-spinner"></div>
                    <span>正在搜索...</span>
                </div>
                <div v-else-if="suggestions.length > 0">
                    <div 
                        v-for="(item, index) in suggestions" 
                        :key="index" 
                        class="suggestion-item"
                        @mousedown.prevent="selectLocation(item)"
                    >
                        {{ item.name }}
                    </div>
                </div>
                <div v-else class="suggestion-empty">
                    <span>未找到相关地址</span>
                </div>
            </div>
        </div>
        
        <!-- 添加经纬度输入框 -->
        <div class="coordinates-input-container">
            <div class="coordinates-input-group">
                <input 
                    type="text" 
                    v-model="inputLng" 
                    placeholder="经度" 
                    class="coordinates-input"
                />
                <input 
                    type="text" 
                    v-model="inputLat" 
                    placeholder="纬度" 
                    class="coordinates-input"
                />
                <button @click="handleCoordinatesSearch" class="coordinates-button" :class="{ 'loading': coordinatesLoading }">
                    <van-icon :name="coordinatesLoading ? 'loading' : 'location'" size="20" />
                </button>
            </div>
        </div>
        
        <!-- 添加随机位置生成功能 -->
        <div class="random-location-container">
            <div class="random-location-group">
                <input 
                    type="number" 
                    v-model="randomDistance" 
                    placeholder="距离" 
                    class="random-distance-input"
                />
                <select v-model="distanceUnit" class="distance-unit-select">
                    <option value="km">公里</option>
                    <option value="m">米</option>
                </select>
                <select v-model="randomType" class="random-type-select">
                    <option value="inside">范围内</option>
                    <option value="outside">范围外</option>
                </select>
                <button @click="handleRandomLocation" class="random-location-button" :class="{ 'loading': randomLoading }">
                    <van-icon :name="randomLoading ? 'loading' : 'aim'" size="20" />
                </button>
            </div>
        </div>
    </div>
    <div class="map-container">
        <div id="map-container"></div>
        <button @click="getCurrentLocation" class="location-button" :class="{ 'loading': loading }">
            <van-icon :name="loading ? 'loading' : 'location-o'" size="24" />
        </button>
        
        <!-- 添加地图缩放按钮 -->
        <div class="zoom-controls">
            <button @click="zoomIn" class="zoom-button">
                <van-icon name="plus" size="20" />
            </button>
            <button @click="zoomOut" class="zoom-button">
                <van-icon name="minus" size="20" />
            </button>
        </div>
        
        <div v-if="loading || searchLoading || coordinatesLoading || randomLoading" class="loading-overlay">
            <div class="loading-spinner"></div>
            <p>{{ 
                loading ? '正在获取位置...' : 
                searchLoading ? '正在搜索地址...' : 
                coordinatesLoading ? '正在定位坐标...' :
                '正在生成随机位置...'
            }}</p>
        </div>
    </div>
    
    <!-- 错误信息弹窗 -->
    <div v-if="errorMessage" class="error-modal">
        <div class="error-modal-content">
            <div class="error-modal-header">
                <van-icon name="warning-o" size="24" color="#ff4d4f" />
                <h3>提示</h3>
            </div>
            <div class="error-modal-body">
                <p>{{ errorMessage }}</p>
            </div>
            <div class="error-modal-footer">
                <button @click="closeErrorModal" class="error-modal-button">确定</button>
            </div>
        </div>
    </div>
    
    <!-- <div v-if="currentLatLng.lng && currentLatLng.lat" class="coordinates-info">
        <p>当前经度: {{ currentLatLng.lng }}</p>
        <p>当前纬度: {{ currentLatLng.lat }}</p>
    </div>
    <div v-if="clickedLatLng.lng && clickedLatLng.lat" class="coordinates-info">
        <p>点击位置经度: {{ clickedLatLng.lng }}</p>
        <p>点击位置纬度: {{ clickedLatLng.lat }}</p>
    </div> -->
</template>

<script setup>
import { onMounted, ref, defineProps, defineEmits, watch } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { Icon as VanIcon } from 'vant';

// 定义组件属性
const props = defineProps({
    // 初始中心点
    initialCenter: {
        type: Array,
        default: () => [116.397428, 39.90923]
    },
    // 初始缩放级别
    initialZoom: {
        type: Number,
        default: 11
    },
    // 是否显示搜索框
    showSearch: {
        type: Boolean,
        default: true
    },
    // 是否显示经纬度输入
    showCoordinates: {
        type: Boolean,
        default: true
    },
    // 是否显示随机位置生成
    showRandomLocation: {
        type: Boolean,
        default: true
    },
    // 地图高度
    mapHeight: {
        type: String,
        default: '400px'
    },
    // 地图API密钥
    apiKey: {
        type: String,
        default: import.meta.env.VITE_API_KEY
    },
    // 安全密钥
    securityJsCode: {
        type: String,
        default: import.meta.env.VITE_SECURITY_JS_CODE
    },
    // 圆形区域基础半径（米）
    circleRadius: {
        type: Number,
        default: 500
    },
    // 是否根据缩放级别动态调整圆形区域大小
    dynamicCircleSize: {
        type: Boolean,
        default: true
    },
    // 圆形区域边框颜色
    circleStrokeColor: {
        type: String,
        default: "#FF33FF"
    },
    // 圆形区域填充颜色
    circleFillColor: {
        type: String,
        default: "#1791fc"
    },
    // 圆形区域边框透明度
    circleStrokeOpacity: {
        type: Number,
        default: 1
    },
    // 圆形区域填充透明度
    circleFillOpacity: {
        type: Number,
        default: 0.35
    }
});

// 定义事件
const emit = defineEmits([
    'location-updated',
    'location-clicked',
    'search-completed',
    'error'
]);

const map = ref(null);
const currentLatLng = ref({ lng: null, lat: null });
const clickedLatLng = ref({ lng: null, lat: null });
const loading = ref(false);
const searchLoading = ref(false);
const errorMessage = ref('');
const currentMarker = ref(null);
const currentCircle = ref(null);
const searchKeyword = ref('');
const suggestions = ref([]);
const showSuggestions = ref(false);
const autoComplete = ref(null);
const searching = ref(false);

// 添加经纬度输入相关的响应式变量
const inputLng = ref('');
const inputLat = ref('');
const coordinatesLoading = ref(false);
const randomDistance = ref('');
const randomType = ref('inside');
const randomLoading = ref(false);

// 添加距离单位选择
const distanceUnit = ref('km');

// 监听位置变化，向父组件发送事件
watch([currentLatLng, clickedLatLng], ([newCurrent, newClicked]) => {
    if (newCurrent.lng && newCurrent.lat) {
        emit('location-updated', { ...newCurrent });
    }
    if (newClicked.lng && newClicked.lat) {
        emit('location-clicked', { ...newClicked });
    }
});

onMounted(() => {
    initMap();
    
});

const initMap = () => {
    window._AMapSecurityConfig = {
        securityJsCode: props.securityJsCode,
    };
    AMapLoader.load({
        key: props.apiKey,
        version: "2.0",
        plugins: ["AMap.Scale", "AMap.Geolocation", "AMap.Marker", "AMap.Circle", "AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Geocoder"],
    })
    .then((AMap) => {
        map.value = new AMap.Map("map-container", {
            viewMode: "3D",
            zoom: props.initialZoom,
        });

        // 初始化自动完成
        autoComplete.value = new AMap.AutoComplete({
            city: '全国'
        });

        // 设置默认中心
        map.value.setCenter(props.initialCenter);
        map.value.setZoom(props.initialZoom);
        
        // 添加地图点击事件监听
        map.value.on('click', (e) => {
            const lnglat = e.lnglat;
            
            // 更新点击位置的经纬度
            clickedLatLng.value = {
                lng: lnglat.lng,
                lat: lnglat.lat
            };
            
            // 移除之前的标记
            if (currentMarker.value) {
                currentMarker.value.setMap(null);
            }
            
            // 创建新的标记
            currentMarker.value = new AMap.Marker({
                position: [lnglat.lng, lnglat.lat],
                title: '点击位置',
                map: map.value
            });
            
            // 绘制圆形区域
            drawCircle([lnglat.lng, lnglat.lat]);
            
            // 使用逆地理编码获取地址信息
            const geocoder = new AMap.Geocoder({
                radius: 100, // 搜索半径，单位：米
                extensions: 'all' // 返回详细信息
            });
            
            geocoder.getAddress([lnglat.lng, lnglat.lat], (status, result) => {
                if (status === 'complete' && result.regeocode) {
                    const address = result.regeocode;
                    console.log('kkkkkkkk');
                    console.log(result);
                    
                    
                    // 提取更详细的地址信息
                    let detailedAddress = address.formattedAddress || '';
                    let buildingInfo = '';
                    let communityInfo = '';
                    
                    // 尝试提取小区信息
                    if (address.addressComponent && address.addressComponent.neighborhood) {
                        communityInfo = address.addressComponent.neighborhood.name || '';
                    }
                    
                    // 尝试提取楼栋信息
                    if (address.pois && address.pois.length > 0) {
                        // 查找最近的POI点
                        const nearestPoi = address.pois[0];
                        if (nearestPoi.name && nearestPoi.type && 
                            (nearestPoi.type.includes('住宅区') || 
                             nearestPoi.type.includes('小区') || 
                             nearestPoi.type.includes('楼') || 
                             nearestPoi.type.includes('大厦'))) {
                            buildingInfo = nearestPoi.name;
                        }
                    }
                    
                    // 组合详细地址
                    let fullAddress = detailedAddress;
                    if (communityInfo && !fullAddress.includes(communityInfo)) {
                        fullAddress = `${communityInfo}，${fullAddress}`;
                    }
                    if (buildingInfo && !fullAddress.includes(buildingInfo)) {
                        fullAddress = `${buildingInfo}，${fullAddress}`;
                    }
                    
                    // 发送位置点击事件，包含详细地址信息
                    emit('location-clicked', {
                        lng: lnglat.lng,
                        lat: lnglat.lat,
                        name: buildingInfo || communityInfo || '点击位置',
                        address: fullAddress,
                        details: {
                            community: communityInfo,
                            building: buildingInfo,
                            formattedAddress: detailedAddress,
                            addressComponent: address.addressComponent
                        }
                    });
                } else {
                    // 如果逆地理编码失败，只发送经纬度信息
                    emit('location-clicked', {
                        lng: lnglat.lng,
                        lat: lnglat.lat
                    });
                }
            });
        });
        
        // 添加地图缩放事件监听
        map.value.on('zoomend', () => {
            // 当缩放级别变化时，重新绘制圆形区域
            if (currentMarker.value && currentMarker.value.getPosition()) {
                const position = currentMarker.value.getPosition();
                drawCircle([position.lng, position.lat]);
            }
        });
    })
    .catch((e) => {
        console.log(e);
        errorMessage.value = "地图加载失败，请刷新页面重试";
        emit('error', "地图加载失败，请刷新页面重试");
    });
};

const handleInput = () => {
    if (!searchKeyword.value) {
        suggestions.value = [];
        showSuggestions.value = false;
        return;
    }

    if (autoComplete.value) {
        searching.value = true;
        showSuggestions.value = true;
        
        autoComplete.value.search(searchKeyword.value, (status, result) => {
            searching.value = false;
            if (status === 'complete' && result.tips) {
                suggestions.value = result.tips;
            } else {
                suggestions.value = [];
            }
        });
    }
};

const handleBlur = () => {
    // 延迟关闭联想列表，以便点击事件能够触发
    setTimeout(() => {
        showSuggestions.value = false;
    }, 200);
};

const selectLocation = (item) => {
    if (!map.value) {
        errorMessage.value = "地图未初始化，请刷新页面重试";
        emit('error', "地图未初始化，请刷新页面重试");
        return;
    }

    const placeSearch = new AMap.PlaceSearch({
        city: '全国'
    });

    // 更新搜索框的值
    searchKeyword.value = item.name;
    showSuggestions.value = false;

    placeSearch.search(item.name, (status, result) => {
        if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
            const poi = result.poiList.pois[0];
            const position = [poi.location.lng, poi.location.lat];
            
            // 更新地图中心点和缩放级别
            map.value.setCenter(position);
            map.value.setZoom(16);

            // 移除之前的标记
            if (currentMarker.value) {
                currentMarker.value.setMap(null);
            }

            // 创建新的标记
            currentMarker.value = new AMap.Marker({
                position: position,
                title: poi.name,
                map: map.value
            });

            // 绘制圆形区域
            drawCircle(position);

            // 更新经纬度显示
            clickedLatLng.value = {
                lng: poi.location.lng,
                lat: poi.location.lat
            };
            
            // 发送搜索完成事件
            emit('search-completed', {
                name: poi.name,
                address: poi.address,
                location: {
                    lng: poi.location.lng,
                    lat: poi.location.lat
                }
            });
        } else {
            errorMessage.value = "未找到该地址的详细信息";
            emit('error', "未找到该地址的详细信息");
        }
    });
};

const drawCircle = (position) => {
    // 移除之前的圆形区域
    if (currentCircle.value) {
        currentCircle.value.setMap(null);
    }

    const AMap = window.AMap;
    
    // 根据当前缩放级别计算圆形区域半径
    let radius = props.circleRadius; // 使用传入的基础半径
    
    // 如果启用了动态大小调整，则根据缩放级别调整半径
    if (props.dynamicCircleSize && map.value) {
        const zoom = map.value.getZoom();
        // 根据缩放级别调整半径
        // 缩放级别越大，半径越小
        radius = Math.max(100, props.circleRadius / Math.pow(1.5, zoom - 11));
    }
    
    // 创建圆形区域
    currentCircle.value = new AMap.Circle({
        center: position,
        radius: radius, // 计算后的半径
        strokeColor: props.circleStrokeColor, // 使用传入的边框颜色
        strokeWeight: 2, // 线条宽度
        strokeOpacity: props.circleStrokeOpacity, // 使用传入的边框透明度
        fillColor: props.circleFillColor, // 使用传入的填充颜色
        fillOpacity: props.circleFillOpacity // 使用传入的填充透明度
    });

    // 将圆形区域添加到地图上
    currentCircle.value.setMap(map.value);
};

const getCurrentLocation = () => {
    loading.value = true;
    errorMessage.value = '';

    if (map.value) {
        const AMap = window.AMap;
        const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
        });

        const getPosition = () => {
            return new Promise((resolve, reject) => {
                geolocation.getCurrentPosition((status, result) => {
                    if (status === 'complete' && result.position) {
                        resolve(result);
                    } else {
                        reject(new Error(result.message || '定位失败'));
                    }
                });
            });
        };

        getPosition()
            .then(result => {
                currentLatLng.value = {
                    lng: result.position.lng,
                    lat: result.position.lat
                };
                
                // 同时更新点击位置，使其成为随机范围定位的中心点
                clickedLatLng.value = {
                    lng: result.position.lng,
                    lat: result.position.lat
                };
                
                map.value.setCenter([result.position.lng, result.position.lat]);
                map.value.setZoom(16);

                if (currentMarker.value) {
                    currentMarker.value.setMap(null);
                }

                currentMarker.value = new AMap.Marker({
                    position: [result.position.lng, result.position.lat],
                    title: '当前位置',
                    map: map.value
                });

                drawCircle([result.position.lng, result.position.lat]);
                
                // 发送位置更新事件
                emit('location-clicked', {
                    lng: result.position.lng,
                    lat: result.position.lat,
                    name: '当前位置',
                    address: '自动获取的当前位置'
                });
            })
            .catch(error => {
                errorMessage.value = `定位失败: ${error.message}`;
                emit('error', `定位失败: ${error.message}`);
                console.error('定位失败:', error);
            })
            .finally(() => {
                loading.value = false;
            });
    } else {
        loading.value = false;
        errorMessage.value = "地图未初始化，请刷新页面重试";
        emit('error', "地图未初始化，请刷新页面重试");
    }
};

const handleSearchButton = () => {
    if (!searchKeyword.value) {
        return;
    }
    
    showSuggestions.value = false;
    searchLoading.value = true;
    errorMessage.value = '';
    
    if (map.value) {
        const placeSearch = new AMap.PlaceSearch({
            city: '全国'
        });

        placeSearch.search(searchKeyword.value, (status, result) => {
            searchLoading.value = false;
            
            if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
                const poi = result.poiList.pois[0];
                const position = [poi.location.lng, poi.location.lat];
                
                map.value.setCenter(position);
                map.value.setZoom(16);

                if (currentMarker.value) {
                    currentMarker.value.setMap(null);
                }

                currentMarker.value = new AMap.Marker({
                    position: position,
                    title: poi.name,
                    map: map.value
                });

                drawCircle(position);

                clickedLatLng.value = {
                    lng: poi.location.lng,
                    lat: poi.location.lat
                };
                
                // 发送搜索完成事件
                emit('search-completed', {
                    name: poi.name,
                    address: poi.address,
                    location: {
                        lng: poi.location.lng,
                        lat: poi.location.lat
                    }
                });
            } else {
                errorMessage.value = "未找到该地址的详细信息";
                emit('error', "未找到该地址的详细信息");
            }
        });
    } else {
        searchLoading.value = false;
        errorMessage.value = "地图未初始化，请刷新页面重试";
        emit('error', "地图未初始化，请刷新页面重试");
    }
};

// 添加经纬度搜索函数
const handleCoordinatesSearch = () => {
    // 验证输入
    if (!inputLng.value || !inputLat.value) {
        errorMessage.value = "请输入完整的经纬度";
        emit('error', "请输入完整的经纬度");
        return;
    }
    
    // 转换为数字并验证
    const lng = parseFloat(inputLng.value);
    const lat = parseFloat(inputLat.value);
    
    if (isNaN(lng) || isNaN(lat)) {
        errorMessage.value = "请输入有效的经纬度数值";
        emit('error', "请输入有效的经纬度数值");
        return;
    }
    
    // 验证经纬度范围
    if (lng < -180 || lng > 180) {
        errorMessage.value = "经度必须在-180到180之间";
        emit('error', "经度必须在-180到180之间");
        return;
    }
    
    if (lat < -90 || lat > 90) {
        errorMessage.value = "纬度必须在-90到90之间";
        emit('error', "纬度必须在-90到90之间");
        return;
    }
    
    // 设置加载状态
    coordinatesLoading.value = true;
    errorMessage.value = '';
    
    if (map.value) {
        const position = [lng, lat];
        
        // 更新地图中心点和缩放级别
        map.value.setCenter(position);
        map.value.setZoom(16);
        
        // 移除之前的标记
        if (currentMarker.value) {
            currentMarker.value.setMap(null);
        }
        
        // 创建新的标记
        currentMarker.value = new AMap.Marker({
            position: position,
            title: '指定位置',
            map: map.value
        });
        
        // 绘制圆形区域
        drawCircle(position);
        
        // 更新经纬度显示
        clickedLatLng.value = {
            lng: lng,
            lat: lat
        };
        
        // 关闭加载状态
        coordinatesLoading.value = false;
        
        // 返回位置信息
        return {
            name: '指定位置',
            address: '通过经纬度指定的位置',
            location: {
                lng: lng,
                lat: lat
            }
        };
    } else {
        coordinatesLoading.value = false;
        errorMessage.value = "地图未初始化，请刷新页面重试";
        emit('error', "地图未初始化，请刷新页面重试");
        return null;
    }
};

// 添加根据经纬度查询位置信息的方法
const geocodeLocation = (lng, lat) => {
    return new Promise((resolve, reject) => {
        if (!map.value) {
            reject(new Error("地图未初始化"));
            return;
        }
        
        // 验证经纬度
        if (isNaN(lng) || isNaN(lat) || lng < -180 || lng > 180 || lat < -90 || lat > 90) {
            reject(new Error("无效的经纬度"));
            return;
        }
        
        const position = [lng, lat];
        
        // 使用逆地理编码获取地址信息
        const AMap = window.AMap;
        const geocoder = new AMap.Geocoder({
            radius: 100, // 搜索半径，单位：米
            extensions: 'all' // 返回详细信息
        });
        
        geocoder.getAddress(position, (status, result) => {
            if (status === 'complete' && result.regeocode) {
                const address = result.regeocode;
                
                // 提取更详细的地址信息
                let detailedAddress = address.formattedAddress || '';
                let buildingInfo = '';
                let communityInfo = '';
                
                // 尝试提取小区信息
                if (address.addressComponent && address.addressComponent.neighborhood) {
                    communityInfo = address.addressComponent.neighborhood.name || '';
                }
                
                // 尝试提取楼栋信息
                if (address.pois && address.pois.length > 0) {
                    // 查找最近的POI点
                    const nearestPoi = address.pois[0];
                    if (nearestPoi.name && nearestPoi.type && 
                        (nearestPoi.type.includes('住宅区') || 
                         nearestPoi.type.includes('小区') || 
                         nearestPoi.type.includes('楼') || 
                         nearestPoi.type.includes('大厦'))) {
                        buildingInfo = nearestPoi.name;
                    }
                }
                
                // 组合详细地址
                let fullAddress = detailedAddress;
                if (communityInfo && !fullAddress.includes(communityInfo)) {
                    fullAddress = `${communityInfo}，${fullAddress}`;
                }
                if (buildingInfo && !fullAddress.includes(buildingInfo)) {
                    fullAddress = `${buildingInfo}，${fullAddress}`;
                }
                
                resolve({
                    name: buildingInfo || communityInfo || '点击位置',
                    address: fullAddress,
                    location: {
                        lng: lng,
                        lat: lat
                    },
                    // 添加更多详细信息
                    details: {
                        community: communityInfo,
                        building: buildingInfo,
                        formattedAddress: detailedAddress,
                        addressComponent: address.addressComponent
                    }
                });
            } else {
                // 如果逆地理编码失败，至少返回经纬度信息
                resolve({
                    name: '点击位置',
                    address: '地图上点击的位置',
                    location: {
                        lng: lng,
                        lat: lat
                    }
                });
            }
        });
    });
};

// 计算随机位置
const calculateRandomLocation = (centerLng, centerLat, distance, isInside) => {
    // 将公里转换为度（粗略计算）
    const degreePerKm = 1 / 111.32; // 1度约等于111.32公里
    
    // 生成随机角度（0-360度）
    const angle = Math.random() * 2 * Math.PI;
    
    // 计算随机距离
    let randomDistance;
    if (isInside) {
        // 范围内随机
        randomDistance = Math.random() * distance;
    } else {
        // 范围外随机（距离在指定距离的1.2-1.5倍之间）
        randomDistance = distance * (1.2 + Math.random() * 0.3);
    }
    
    // 计算经纬度偏移
    const latOffset = randomDistance * degreePerKm * Math.cos(angle);
    const lngOffset = randomDistance * degreePerKm * Math.sin(angle);
    
    return {
        lng: centerLng + lngOffset,
        lat: centerLat + latOffset
    };
};

// 处理随机位置生成
const handleRandomLocation = () => {
    // 验证输入
    if (!randomDistance.value || randomDistance.value <= 0) {
        errorMessage.value = "请输入有效的距离";
        emit('error', "请输入有效的距离");
        return;
    }
    
    // 检查是否有中心点
    if (!clickedLatLng.value.lng || !clickedLatLng.value.lat) {
        errorMessage.value = "请先选择一个中心点";
        emit('error', "请先选择一个中心点");
        return;
    }
    
    // 设置加载状态
    randomLoading.value = true;
    errorMessage.value = '';
    
    // 转换距离单位
    let distanceInKm = parseFloat(randomDistance.value);
    if (distanceUnit.value === 'm') {
        // 如果选择的是米，转换为公里
        distanceInKm = distanceInKm / 1000;
    }
    
    if (map.value) {
        const isInside = randomType.value === 'inside';
        const randomLocation = calculateRandomLocation(
            clickedLatLng.value.lng,
            clickedLatLng.value.lat,
            distanceInKm,
            isInside
        );
        
        // 更新地图中心点和缩放级别
        map.value.setCenter([randomLocation.lng, randomLocation.lat]);
        map.value.setZoom(14);
        
        // 移除之前的标记
        if (currentMarker.value) {
            currentMarker.value.setMap(null);
        }
        
        // 创建新的标记
        currentMarker.value = new AMap.Marker({
            position: [randomLocation.lng, randomLocation.lat],
            title: isInside ? '范围内随机位置' : '范围外随机位置',
            map: map.value
        });
        
        // 绘制圆形区域
        drawCircle([randomLocation.lng, randomLocation.lat]);
        
        // 更新经纬度显示
        clickedLatLng.value = {
            lng: randomLocation.lng,
            lat: randomLocation.lat
        };
        
        // 关闭加载状态
        randomLoading.value = false;
    } else {
        randomLoading.value = false;
        errorMessage.value = "地图未初始化，请刷新页面重试";
        emit('error', "地图未初始化，请刷新页面重试");
    }
};

// 关闭错误弹窗
const closeErrorModal = () => {
    errorMessage.value = '';
};

// 添加地图缩放方法
const zoomIn = () => {
    if (map.value) {
        const currentZoom = map.value.getZoom();
        map.value.setZoom(currentZoom + 1);
    }
};

const zoomOut = () => {
    if (map.value) {
        const currentZoom = map.value.getZoom();
        if (currentZoom > 1) { // 防止缩放到最小级别以下
            map.value.setZoom(currentZoom - 1);
        }
    }
};

// 暴露方法给父组件
defineExpose({
    getCurrentLocation,
    searchLocation: handleSearchButton,
    searchByCoordinates: handleCoordinatesSearch,
    generateRandomLocation: handleRandomLocation,
    setCenter: (lng, lat, zoom = 16) => {
        if (map.value) {
            map.value.setCenter([lng, lat]);
            map.value.setZoom(zoom);
        }
    },
    addMarker: (lng, lat, title = '标记') => {
        if (map.value) {
            if (currentMarker.value) {
                currentMarker.value.setMap(null);
            }
            
            currentMarker.value = new AMap.Marker({
                position: [lng, lat],
                title: title,
                map: map.value
            });
            
            drawCircle([lng, lat]);
            
            clickedLatLng.value = {
                lng: lng,
                lat: lat
            };
        }
    },
    // 添加根据经纬度查询位置信息的方法
    geocodeLocation,
    // 添加缩放方法到暴露的API中
    zoomIn,
    zoomOut
});
</script>

<style scoped>
.map-container {
    position: relative;
    width: 100%;
    height: v-bind('mapHeight');
}

#map-container {
    width: 100%;
    height: 100%;
}

.location-button {
    position: absolute;
    right: 20px;
    bottom: 20px;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: white;
    border: none;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    z-index: 100;
}

.location-button:hover {
    background-color: #f5f5f5;
}

.location-button.loading {
    animation: rotate 1s linear infinite;
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

.loading-message {
    margin-top: 10px;
    text-align: center;
    color: #666;
}

.error-message {
    margin-top: 10px;
    text-align: center;
    color: #ff4d4f;
}

.coordinates-info {
    margin-top: 10px;
    padding: 10px;
    background-color: #f5f5f5;
    border-radius: 4px;
}

.search-container {
    position: relative;
    width: 100%;
    padding: 10px;
    background-color: #fff;
    z-index: 1000;
}

.search-box {
    position: relative;
    width: 100%;
}

.search-input-wrapper {
    display: flex;
    align-items: center;
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
}

.search-input {
    flex: 1;
    padding: 10px;
    border: none;
    font-size: 14px;
    outline: none;
}

.search-input:focus {
    border: none;
    box-shadow: none;
}

.search-button {
    padding: 10px 15px;
    background-color: #1E9FFF;
    color: white;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

.search-button:hover {
    background-color: #1890ff;
}

.search-button.loading {
    animation: rotate 1s linear infinite;
}

.suggestions-container {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background-color: #fff;
    border: 1px solid #ddd;
    border-top: none;
    border-radius: 0 0 4px 4px;
    max-height: 200px;
    overflow-y: auto;
    z-index: 1000;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.suggestion-item {
    padding: 10px;
    cursor: pointer;
    user-select: none;
}

.suggestion-item:hover {
    background-color: #f5f5f5;
}

.suggestion-item:active {
    background-color: #e6f7ff;
}

.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.8);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    z-index: 99;
}

.loading-spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #1E9FFF;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 10px;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.suggestion-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 15px;
    color: #666;
}

.suggestion-spinner {
    width: 16px;
    height: 16px;
    border: 2px solid #f3f3f3;
    border-top: 2px solid #1E9FFF;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-right: 10px;
}

.suggestion-empty {
    padding: 15px;
    text-align: center;
    color: #999;
}

.coordinates-input-container {
    margin-top: 10px;
    width: 100%;
}

.coordinates-input-group {
    display: flex;
    align-items: center;
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
}

.coordinates-input {
    flex: 1;
    padding: 10px;
    border: none;
    font-size: 14px;
    outline: none;
    border-right: 1px solid #eee;
}

.coordinates-input:focus {
    border: none;
    box-shadow: none;
}

.coordinates-button {
    padding: 10px 15px;
    background-color: #1E9FFF;
    color: white;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

.coordinates-button:hover {
    background-color: #1890ff;
}

.coordinates-button.loading {
    animation: rotate 1s linear infinite;
}

.random-location-container {
    margin-top: 10px;
    width: 100%;
}

.random-location-group {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
}

.random-distance-input {
    width: 30%;
    min-width: 80px;
    padding: 10px;
    border: none;
    font-size: 14px;
    outline: none;
    border-right: 1px solid #eee;
}

.distance-unit-select {
    width: 20%;
    min-width: 70px;
    padding: 10px;
    border: none;
    font-size: 14px;
    outline: none;
    background-color: #f5f5f5;
    border-right: 1px solid #eee;
    cursor: pointer;
}

.random-type-select {
    width: 30%;
    min-width: 80px;
    padding: 10px;
    border: none;
    font-size: 14px;
    outline: none;
    background-color: #f5f5f5;
    border-right: 1px solid #eee;
    cursor: pointer;
}

.random-location-button {
    width: 20%;
    min-width: 50px;
    height: 40px;
    background-color: #1E9FFF;
    color: white;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    -webkit-appearance: none;
    -webkit-tap-highlight-color: transparent;
    user-select: none;
    outline: none;
    box-sizing: border-box;
}

.random-location-button:hover {
    background-color: #1890ff;
}

.random-location-button:active {
    background-color: #1890ff;
}

.random-location-button .van-icon {
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    color: white !important;
    opacity: 1 !important;
    visibility: visible !important;
    pointer-events: none !important;
}

.random-location-button:active .van-icon {
    color: white !important;
    opacity: 1 !important;
    visibility: visible !important;
}

.random-location-button.loading {
    background-color: #1890ff;
}

.random-location-button.loading .van-icon {
    color: white !important;
    opacity: 1 !important;
    visibility: visible !important;
}

@media screen and (max-width: 480px) {
    .random-location-group {
        flex-wrap: nowrap;
    }
    
    .random-distance-input {
        width: 25%;
        min-width: 60px;
        
        padding: 10px 5px;
    }
    
    .distance-unit-select {
        width: 20%;
        min-width: 50px;
        padding: 10px 5px;
    }
    
    .random-type-select {
        width: 35%;
        min-width: 70px;
        padding: 10px 5px;
    }
    
    .random-location-button {
        width: 20%;
        min-width: 40px;
        height: 36px;
        padding: 0;
    }
    
    .random-location-button .van-icon {
        margin: 0;
    }
    
    .coordinates-input-group {
        display: flex;
        align-items: normal;
        flex-direction: column;
        border: 1px solid #ddd;
        border-radius: 4px;
        overflow: hidden;
    }
}

/* 错误弹窗样式 */
.error-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2000;
}

.error-modal-content {
    width: 80%;
    max-width: 320px;
    background-color: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.error-modal-header {
    padding: 16px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
}

.error-modal-header h3 {
    margin: 0 0 0 10px;
    font-size: 16px;
    font-weight: 500;
}

.error-modal-body {
    padding: 16px;
    text-align: center;
}

.error-modal-footer {
    padding: 12px 16px;
    text-align: right;
    border-top: 1px solid #f0f0f0;
}

.error-modal-button {
    padding: 6px 16px;
    background-color: #1E9FFF;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

.error-modal-button:hover {
    background-color: #1890ff;
}

/* 添加缩放按钮样式 */
.zoom-controls {
    position: absolute;
    right: 20px;
    bottom: 70px; /* 位于定位按钮上方 */
    display: flex;
    flex-direction: column;
    z-index: 100;
}

.zoom-button {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: white;
    border: none;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    margin-bottom: 5px;
}

.zoom-button:hover {
    background-color: #f5f5f5;
}

.zoom-button:active {
    background-color: #e6e6e6;
}
</style>
